package cn.xlmdz.subsoilerinfoquery.http;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import cn.xlmdz.subsoilerinfoquery.app.Constants;
import cn.xlmdz.subsoilerinfoquery.app.MyApplication;
import okhttp3.Cache;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.Buffer;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiEngine {
    private volatile static ApiEngine apiEngine;
    private Retrofit retrofit;

    private ApiEngine() {
        //日志拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        //缓存
        int size = 1024 * 1024 * 100;
        File cacheFile = new File(MyApplication.getAppContext().getCacheDir(), "OkHttpCache");
        Cache cache = new Cache(cacheFile, size);

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(12, TimeUnit.SECONDS)
                .readTimeout(12, TimeUnit.SECONDS)
                .writeTimeout(12, TimeUnit.SECONDS)
                .addNetworkInterceptor(new NetworkInterceptor()) //网络缓存设置
                .addInterceptor(loggingInterceptor)
                .addInterceptor(chain -> { //添加公共请求参数
                    Request request = chain.request();

                    /*//设备唯一id，在应用启动生成
                    String android_id = mmkv.decodeString("android_id", "android_id==null");
                    //当前版本号
                    String ver = mmkv.decodeString("ver", "ver==null");*/

                    if (request.method().equals("POST")) {//POST公共请求参数
                        Request.Builder requestBuilder = request.newBuilder();
                        RequestBody formBody = new FormBody.Builder()
                                .add("os", "android")
                                /*.add("ukey", android_id)
                                .add("ver", ver)*/
                                .build();

                        String postBodyString = bodyToString(request.body());
                        postBodyString += ((postBodyString.length() > 0) ? "&" : "") + bodyToString(formBody);
                        requestBuilder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), postBodyString));
                        request = requestBuilder.build();
                    }
                    return chain.proceed(request);
                })
                .cache(cache)
                .build();

        retrofit = new Retrofit.Builder()
                .baseUrl(Constants.API_HOST)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .build();
    }

    public static ApiEngine getInstance() {
        if (apiEngine == null) {
            synchronized (ApiEngine.class) {
                if (apiEngine == null) {
                    apiEngine = new ApiEngine();
                }
            }
        }
        return apiEngine;
    }

    public ApiServices getApiService() {
        return retrofit.create(ApiServices.class);
    }

    /**
     * post 在body添加参数
     *
     * @param request
     * @return
     */
    private static String bodyToString(final RequestBody request) {
        try {
            final RequestBody copy = request;
            final Buffer buffer = new Buffer();
            if (copy != null)
                copy.writeTo(buffer);
            else
                return "";
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }
}
